package volatileT;

import java.util.concurrent.atomic.AtomicInteger;

public class demo2 {
    //解决原子性问题
    private  static AtomicInteger num = new AtomicInteger();
    //private volatile static int num = 0;
    private static void add() {
        //num++;
        num.getAndIncrement();
    }
    public static void main(String[] args) {
        for (int i = 1; i <= 20; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 1000; i1++) {
                    add();
                }
            }).start();
        }
        //有main和gc线程在跑,若大于2,则礼让,确保不会抢线程
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+" 计算总和="+num);

    }
}
